#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <mutex>
#include<algorithm>
#include <cassert>
#include <fstream>
#include <jsoncpp/json/json.h>

#include "oj_model2.hpp"
#include "oj_view.hpp"
#include "../comm/Util.hpp"
#include "../comm/log.hpp"
#include "../comm/httplib.h"

namespace ns_control
{
    using namespace std;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;
    // 负载均衡
    // 提供服务的主机
    class Machine
    {
    public:
        string _ip;     // 主机的ip
        uint64_t _load; // 编译服务的负载
        int _port;      // 主机的端口号
        mutex *_mtx;    // mutex禁止拷贝
        Machine() : _ip(" "), _load(0), _port(0), _mtx(nullptr)
        {
        }
        ~Machine()
        {
        }
        void IncLoad()
        {
            if (_mtx) _mtx->lock();
            _load++;
            if (_mtx)  _mtx->unlock();
        }
        void DecLoad()
        {
            if (_mtx) _mtx->lock();
            _load--;
            if (_mtx) _mtx->unlock();
        }
        void ResetLoad()
        {
            if (_mtx) _mtx->lock();
            _load=0;
            if (_mtx) _mtx->unlock();
        }
        uint64_t Load()
        {
            uint64_t load = 0;
            if (_mtx) _mtx->lock();
            load = _load;
            if (_mtx) _mtx->unlock();
            return load;
        }
    };
    const string service_conf = "./conf/service.conf";
    // 提供负载均衡
    class LoadBlance
    {
    private:
        // 提供编译服务的所有主机
        // 每台主机都自己的下标，充当主机的ip
        vector<Machine> _Machine;
        vector<int> _online;  // 所有在线的主机id
        vector<int> _offline; // 所有离线的主机id
        mutex _mtx;

    public:
        LoadBlance()
        {
            assert(LoadConf(service_conf));
            LOG(INFO) << "加载 " << service_conf << " 成功 " << "\n";
        }
        ~LoadBlance()
        {
        }

    public:
        bool LoadConf(const string &machine_conf)
        {
            ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载 " << machine_conf << " 失败 " << "\n";
                return false;
            }
            string line;
            while (getline(in, line))
            {
                vector<string> tokens;
                StringUtil::SpiltString(line, &tokens, ":"); // 拆分
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分失败" << "\n";
                    continue;
                }
                Machine m;
                m._ip = tokens[0];
                m._port = atoi(tokens[1].c_str());
                m._load = 0;
                m._mtx = new mutex();
                _online.push_back(_Machine.size());
                _Machine.push_back(m);
            }
            in.close();
            return true;
        }
        bool SmartChoice(int *id, Machine **m)
        {
            // 选择更好的主机，需要更新主机的负载
            _mtx.lock();
            // 负载均衡算法
            // 轮询+hash
            // 随机数+hash
            int online_num = _online.size();
            if (online_num == 0)
            {
                printf("online_num\n");
                _mtx.unlock();
                LOG(FATAL) << "所有的后端编译主机已经离线" << "\n";
                return false;
            }
            // 遍历的方式
            // 初始化
            *id = _online[0];
            *m = &_Machine[_online[0]];
            uint64_t minload = _Machine[_online[0]].Load();
            for (int i = 1; i < online_num; i++)
            {
                uint64_t curr_load = _Machine[_online[i]].Load();
                // cout<<"curr_load: "<<curr_load<<endl;
                if (minload >curr_load)
                {
                    minload = curr_load;
                    *id = _online[i];
                    *m = &_Machine[_online[i]];
                }
                // cout<<"compared"<<endl;
            }
            _mtx.unlock();
            return true;
        }
        void OfflineMachine(int which)
        {
            // 防止同时操作
            _mtx.lock();
            for (auto iter = _online.begin(); iter != _online.end(); iter++)
            {
                if (*iter == which)
                {
                    // 只需要将在在线主机中删除,离线主机中++
                    _online.erase(iter);
                    _offline.push_back(which);
                    break;
                }
            }
            _mtx.unlock();
        }
        void OnlineMachine()
        {
            //我们统一上线，后面统一解决
            _mtx.lock();
            _online.insert(_online.end(), _offline.begin(), _offline.end());
            _offline.erase(_offline.begin(), _offline.end());
            _mtx.unlock();
            LOG(INFO) << "所有的主机有上线啦!" << "\n";
        }
        void ShowMachine()
        {
            _mtx.lock();
            cout << "主机在线列表：";
            for (auto &id : _online)
            {
                cout << id << " ";
            }
            cout << endl;
            cout << "离线主机在线：";
            for (auto &id : _offline)
            {
                cout << id << " ";
            }
            cout << endl;
            _mtx.unlock();
        }
    };
    // 核心--控制器
    class Control
    {
    public:
        Control()
        {
        }
        ~Control()
        {
        }
        void RecoveryMachine()
        {
            _ld.OnlineMachine();
        }
        bool AllQuestion(string *html)
        {
            vector<struct Question> all;
            bool ret = true;
            if (_model.GetAllQuestions(&all))
            {
                // 获取题目信息成功，返回全是题目的网页
                sort(all.begin(),all.end(),[](const struct Question &q1,const struct Question &q2) {
                    return atoi(q1.number.c_str())<atoi(q2.number.c_str());
                });
                _view.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题目失败, 形成题目列表失败";
                ret = false;
            }
            return ret;
        }
        bool Question(string &num, string *html)
        {
            class Question q;
            bool ret = true;
            if (_model.GetOneQuest(num, &q))
            {
                _view.OneExpandHtml(q, html);
            }
            else
            {
                *html = "指定题目: " + num + " 不存在!";
                ret = false;
            }
            return ret;
        }
        // code:"#include...."
        // input:....
        void Judge(string &num, string in_json, string *out_json)
        {
            // LOG(DEBUG) << in_json << " \nnumber:" << num << "\n";
            struct Question q;
            // 0.通过题目编号找到对应题
            _model.GetOneQuest(num, &q);

            // 1.对in_json进行反序列
            Json ::Value in_value;
            Json::Reader reader;
            reader.parse(in_json, in_value);
            string code = in_value["code"].asString();
            // 重新拼接代码
            Json ::Value complie;
            complie["code"] = code +"\n" + "#define _COM_ONLINE 1\n" + q.tail; 
            complie["input"] = in_value["input"].asString();
            complie["cpu_lim"] = q.cpu_lim;
            complie["mem_lim"] = q.mem_lim;
            Json::FastWriter writer;
            string complie_string = writer.write(complie);
            // 选择负载最低的机器
            // 规则：一直选择，直至主机可用
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_ld.SmartChoice(&id, &m))
                {
                    break;     
                }
                // 发起http请求
                Client cli(m->_ip, m->_port);
                m->IncLoad();
                // LOG(INFO) << "选择主机成功,主机id:" << m->_ip << ":" << m->_port << "\n";
                LOG(INFO) << " 选择主机成功, 主机id: " << id << " 详情: " << m->_ip << ":" << m->_port << " 当前主机的负载是: " << m->Load() << "\n";
                if (auto res = cli.Post("/complie_and_run", complie_string, "application/json;charset=utf-8"))
                {
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译和运行服务成功" << "\n";
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "当前请求的主机id:" << m->_ip << ":" << m->_port << "可能离线了" << "\n";
                    _ld.OfflineMachine(id);
                    _ld.ShowMachine();
                }
            }
        }

    private:
        Model _model;
        View _view;
        LoadBlance _ld;
    };
}